import java.util.Arrays;

public class Heap {
    public int[] elem;
    public int usedSize;

    public Heap(){
        this.elem = new int[10];
    }

    public void getNum(int[] array){
        for (int i = 0; i < array.length; i++) {
            elem[i] = array[i];
            usedSize++;
        }
    }

    public void getHeap(){
        for (int parent = (usedSize - 1 - 1) / 2; parent >= 0; parent--) {
            outHeap(parent, usedSize);
        }
    }

    public void outHeap(int parent, int len){
        int child = 2 * parent + 1;
        while (child < len){
            if (child + 1 < len && elem[child] < elem[child + 1]){
                child++;
            }
            if (elem[child] > elem[parent]){
                int tmp = elem[child];
                elem[child] = elem[parent];
                elem[parent] = tmp;
                parent = child;
                child = parent * 2 + 1;
            }
            else {
                break;
            }
        }
    }

    //插入新元素
    public void shift(int val){
        if (isFull()){
            elem = Arrays.copyOf(elem, elem.length*2);
        }
        elem[usedSize] = val;
        usedSize++;
        shiftDown(--usedSize);
    }
    //向上调整
    private void shiftDown(int child){
        int parent = (child - 1) / 2;
        while (child > 0){
            if (elem[parent] < elem[child]){
                int tmp = elem[parent];
                elem[parent] = elem[child];
                elem[child] = tmp;
                child = parent;
                parent = (child - 1) / 2;
            }
            else {
                break;
            }
        }
    }

    //先判断是否为满
    public boolean isFull(){
        return usedSize == elem.length;
    }

    //删除节点
    public void pop(){
        if (isEmpty()){
            return;
        }
        int tmp = elem[0];
        elem[0] = elem[usedSize - 1];
        elem[usedSize - 1] = tmp;
        usedSize--;
        outHeap(0, usedSize);
    }

    //是否为空
    public boolean isEmpty(){
        return usedSize == 0;
    }

    //堆排序由小到大排序
    public void smallTo(){
        int end = usedSize - 1;
        while (end > 0){
            int tmp = elem[0];
            elem[0] = elem[end];
            elem[end] = tmp;
            outHeap(0, end);
            end--;
        }
    }
















}
